package com.bw.kotlindemo.java.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseFragment<VM extends ViewModel, DBD extends ViewDataBinding>
        extends Fragment {

    //创建
    public VM mViewModel;
    public DBD mDataBinding;
    public Context activity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
    }

    //创建

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        //获取页面
        mDataBinding = DataBindingUtil.inflate(inflater, initLayout(), container, false);
        return mDataBinding.getRoot();
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        initViewModel();
//        initData();
//    }

    //创建
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViewModel();
        initData();
    }

    protected abstract void initData();

    protected void initViewModel() {
        if (mViewModel == null) {
            Class cla = null;
            final Type type = getClass().getGenericSuperclass();

            if (type instanceof ParameterizedType) {
                cla = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
            } else {
                cla = getClass();
            }
            mViewModel = (VM) ViewModelProviders.of(this).get(cla);
        }
    }

    ;

    protected abstract int initLayout();
}